{% extends "base.html" %}

{% block title %}短视频去水印解析{% endblock %}

{% block content %}
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css" rel="stylesheet">
<!-- 样式优化 -->
<style>
/* 视频加载中提示 */
.video-loading-wrap {
    position: relative;
}
.video-loading {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: rgba(255,255,255,0.9);
    padding: 10px 20px;
    border-radius: 6px;
    color: #6c757d;
    font-size: 15px;
    z-index: 10;
    display: flex;
    align-items: center;
    gap: 8px;
}
/* 错误提示 */
.video-error {
    margin-top: 8px;
    padding: 10px;
    background-color: #f8d7da;
    color: #721c24;
    border-radius: 4px;
    font-size: 14px;
    text-align: center;
    border: 1px solid #f5c6cb;
}
/* 手动打开引导 */
.manual-guide {
    margin-top: 10px;
    padding: 10px;
    background-color: #fff3cd;
    color: #856404;
    border-radius: 4px;
    font-size: 14px;
    border: 1px solid #ffeeba;
    display: flex;
    align-items: center;
    gap: 8px;
}
/* 图集图片效果 */
.card-img-top {
    transition: transform 0.3s ease;
}
.card:hover .card-img-top {
    transform: scale(1.03);
}
</style>

<div class="container mt-4 mb-5">
    <!-- 公告卡片 -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card shadow-sm border-left-4 border-pink-500">
                <div class="card-body">
                    <h5 class="card-title d-flex align-items-center text-pink-600">
                        <i class="bi bi-bullhorn me-2"></i> 网站公告
                    </h5>
                    <ul class="list-unstyled mb-0">
                        <li class="mb-1"><i class="bi bi-check-circle text-success me-1"></i> 注册账号，轻松获取短视频去水印解析次数</li>
                        <li class="mb-1"><i class="bi bi-code text-info me-1"></i> <strong>目前支持: </strong>抖音/皮皮虾/火山/微视/最右/快手/全民小视频/皮皮搞笑/梨视频/西瓜/微博/虎牙/绿洲/好看/逗拍/美拍/新片场/A站/全民K歌/6间房</li>
                        <li class="mb-1"><i class="bi bi-star text-warning me-1"></i> 开通会员增加更多解析次数，<a href="/user/vip" target="_blank" class="text-pink-600 fw-medium" style="text-decoration: none;">查看详情 <i class="bi bi-arrow-right-short"></i></a></li>
                        <li class="mb-1"><i class="bi bi-tag text-primary me-1"></i> 解析费用低，每日解析单价低至0.007，不到<code class="text-primary">一分钱</code></li>
                        <li class="mb-1"><i class="bi bi-code text-info me-1"></i> 开发者可开通会员后申请接口对接</li>
                        <li><i class="bi bi-weixin text-green-600 me-1"></i> 客服微信：<code class="text-pink-600">tiktoksoft</code></li>
                        <p>
                <strong>温馨提示: </strong><br/>
                1. 粘贴视频地址时<u>无需删除文案</u><small> 但如果视频链接正确但解析失败请删掉文案后重试</small><br/>
                2. 点击下载视频跳转时, 可能会被对应网站识别, 报 <u>403 Forbidden</u>, 可以在 下载视频 按钮, 右键复制链接地址, 新开浏览器标签页打开即可
            </p>
                    </ul>
                </div>
            </div>
        </div>
    </div>

    <!-- 解析主体 -->
    <div class="row">
        <div class="col-12">
            <div class="card shadow-sm">
                <!-- 输入区 -->
                <div class="card-header bg-light">
                    <h5 class="card-title mb-0 d-flex align-items-center">
                        <i class="bi bi-magic text-primary me-2"></i> 视频/图集解析
                    </h5>
                </div>
                <div class="card-body">
                    <div class="input-group mb-3">
                        <input
                            id="url"
                            class="form-control"
                            placeholder="请粘贴短视频/App内复制的链接（支持抖音、快手等主流平台）"
                            aria-label="解析链接"
                        >
                        <button class="btn btn-outline-secondary" type="button" id="clearUrl">
                            <i class="bi bi-x-circle"></i>
                        </button>
                    </div>
                    <button
                        class="btn btn-primary w-100 py-2"
                        id="subjx"
                        style="background-color: #e83e8c; border-color: #e83e8c;"
                    >
                        <i class="bi bi-scissors me-1"></i> 开始去水印
                    </button>

                    <!-- 结果展示区 -->
                    <div class="mt-4">
                        <!-- 作者信息 -->
                        <div id="authorInfo" class="d-none align-items-center mb-3 p-3 bg-light rounded-2">
                            <img id="authorAvatar" src="" alt="作者头像" class="rounded-circle" width="40" height="40">
                            <div class="ms-3">
                                <h6 class="mb-0 fw-medium" id="authorName"></h6>
                                <p class="mb-0 text-sm text-muted" id="authorUid" style="display: none;"></p>
                            </div>
                        </div>

                        <!-- 标题 -->
                        <div id="contentTitle" class="d-none mb-3">
                            <h6 class="fw-medium text-muted">内容标题</h6>
                            <p class="mb-0 p-2 bg-light rounded-2" id="titleText"></p>
                        </div>

                        <!-- 封面预览 -->
                        <div id="coverPreview" class="d-none mb-3 text-center">
                            <h6 class="fw-medium text-muted mb-2">封面预览</h6>
                            <img id="coverImage" src="" alt="封面" class="img-fluid rounded-2" style="max-height: 300px;">
                        </div>

                        <!-- 图集展示 -->
                        <div id="imageGallery" class="d-none mb-3">
                            <h6 class="fw-medium text-muted mb-2">图集（共<span id="imageCount">0</span>张）</h6>
                            <div id="imageContainer" class="d-flex flex-wrap gap-3 justify-content-center"></div>
                        </div>

                        <!-- 资源链接 -->
                        <div class="accordion mt-3" id="resourceUrls" style="display: none;">
                            <div class="card mb-2">
                                <div class="card-header bg-light" data-bs-toggle="collapse" data-bs-target="#collapseCover">
                                    <h6 class="mb-0 d-flex justify-content-between align-items-center">
                                        <span><i class="bi bi-image me-1"></i> 封面图链接</span>
                                        <button class="btn btn-sm btn-outline-primary copy-btn" data-target="coverUrl">
                                            <i class="bi bi-clipboard"></i> 复制
                                        </button>
                                    </h6>
                                </div>
                                <div id="collapseCover" class="collapse show">
                                    <div class="card-body p-2">
                                        <code id="coverUrl" class="d-block w-100 p-2 bg-light rounded-2 overflow-x-auto"></code>
                                    </div>
                                </div>
                            </div>
                            <div id="videoUrlCard" class="card mb-2 d-none">
                                <div class="card-header bg-light" data-bs-toggle="collapse" data-bs-target="#collapseVideo">
                                    <h6 class="mb-0 d-flex justify-content-between align-items-center">
                                        <span><i class="bi bi-file-video me-1"></i> 无水印视频链接</span>
                                        <div>
                                            <a id="videoDownload" href="" class="btn btn-sm btn-danger me-1" target="_blank" download>
                                                <i class="bi bi-download"></i> 下载
                                            </a>
                                            <button class="btn btn-sm btn-outline-primary copy-btn" data-target="videoUrl">
                                                <i class="bi bi-clipboard"></i> 复制
                                            </button>
                                        </div>
                                    </h6>
                                </div>
                                <div id="collapseVideo" class="collapse show">
                                    <div class="card-body p-2">
                                        <code id="videoUrl" class="d-block w-100 p-2 bg-light rounded-2 overflow-x-auto"></code>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- 视频播放区 -->
                        <div id="videoPlayer" class="d-none mb-3">
                            <h6 class="fw-medium text-muted mb-2">无水印视频</h6>
                            <div class="video-loading-wrap ratio ratio-9x16 border rounded-2 overflow-hidden mb-2" id="videoWrap" >
                                <div id="videoLoading" class="video-loading d-none">
                                    <i class="bi bi-hourglass-half"></i> 视频加载中...
                                </div>
                                <video
                                    id="media"
                                    class="w-100 h-100"
                                    controls
                                    preload="auto"
                                    crossorigin="anonymous"
                                >
                                    <source id="videoSourceMain" src="" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'>
                                    <source id="videoSourceBackup" src="" type="video/mp4">
                                    您的浏览器不支持视频播放，请更换Chrome/Edge等现代浏览器重试
                                </video>
                            </div>
                            <div id="videoError" class="video-error d-none"></div>
                            <div id="manualGuide" class="manual-guide d-none">
                                <i class="bi bi-lightbulb"></i> 提示：可复制地址后在新浏览器窗口粘贴打开
                            </div>
                            <div class="d-flex gap-2">
                                <a id="videoDownloadPlayer" href="" class="btn btn-danger flex-fill" target="_blank" download>
                                    <i class="bi bi-download"></i> 下载视频
                                </a>
                                <button class="btn btn-outline-primary flex-fill copy-btn" data-target="videoUrl">
                                    <i class="bi bi-clipboard"></i> 复制地址
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script type="text/javascript">
    // 消息提示
    function message(type, text) {
        const iconMap = {
            success: '<i class="bi bi-check-circle-fill me-1"></i>',
            error: '<i class="bi bi-exclamation-circle-fill me-1"></i>'
        };
        const div = document.createElement('div');
        div.className = 'alert alert-' + type + ' alert-dismissible fade show';
        div.role = 'alert';
        div.innerHTML = `${iconMap[type]}${text}
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>`;
        div.style.position = 'fixed';
        div.style.top = '20px';
        div.style.left = '50%';
        div.style.transform = 'translateX(-50%)';
        div.style.zIndex = '9999';
        div.style.minWidth = '300px';
        document.body.appendChild(div);
        setTimeout(() => {
            div.classList.remove('show');
            setTimeout(() => div.remove(), 500);
        }, 3000);
    }

    // 按钮状态控制
    function setButtonStatus(btnSelector, isDisabled, text = '去水印') {
        const btn = document.querySelector(btnSelector);
        if (isDisabled) {
            btn.disabled = true;
            btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span> ' + text;
        } else {
            btn.disabled = false;
            btn.innerHTML = text;
        }
    }

    // 清空输入框
    document.getElementById('clearUrl').addEventListener('click', () => {
        document.getElementById('url').value = '';
    });

    // 粘贴自动去空格
    document.getElementById('url').addEventListener('paste', (e) => {
        e.preventDefault();
        const pastedText = (e.clipboardData || window.clipboardData).getData('text').trim();
        document.getElementById('url').value = pastedText;
    });

    // 复制功能
    document.addEventListener('click', (e) => {
        if (e.target.closest('.copy-btn')) {
            const btn = e.target.closest('.copy-btn');
            const targetId = btn.getAttribute('data-target');
            const text = document.getElementById(targetId).textContent.trim();
            navigator.clipboard.writeText(text)
                .then(() => message('success', '链接复制成功！'))
                .catch(() => {
                    const el = document.getElementById(targetId);
                    const range = document.createRange();
                    range.selectNode(el);
                    window.getSelection().removeAllRanges();
                    window.getSelection().addRange(range);
                    document.execCommand('copy');
                    message('success', '链接复制成功（兼容模式）！');
                });
        }
    });

    // 核心解析逻辑
    document.getElementById('subjx').addEventListener('click', () => {
        const url = document.getElementById('url').value.trim();
        if (!url) {
            message('error', '解析地址不能为空，请粘贴视频链接！');
            return;
        }

        let regex = /http[s]?:\/\/[\w.-]+[\w\/-]*[\w.-]*\??[\w=&:\-\+\%]*[/]*/;
        const url_v = url.match(regex)[0];
        console.log(url_v);

        if (!url_v) {
            message('error', '请输入有效的链接（以http/https开头）！');
            return;
        }

        // 初始化状态
        ['authorInfo','contentTitle','videoPlayer','imageGallery','resourceUrls','videoUrlCard']
            .forEach(id => document.getElementById(id).classList.add('d-none'));
        document.getElementById('imageContainer').innerHTML = '';
        const media = document.getElementById('media');
        if (media) {
            media.pause();
            media.src = '';
        }
        document.getElementById('videoLoading').classList.add('d-none');
        document.getElementById('videoError').classList.add('d-none');
        document.getElementById('manualGuide').classList.add('d-none');
        document.getElementById('authorUid').style.display = 'none';

        setButtonStatus('#subjx', true, '正在解析...');

        // 发起解析请求
        fetch('/video/jiexi', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Referer': window.location.origin,
                'User-Agent': navigator.userAgent,
                'Range': 'bytes=0-'
            },
            body: 'url=' + encodeURIComponent(url_v)
        })
        .then(response => {
            if (!response.ok) throw new Error(`请求失败（状态码：${response.status}）`);
            return response.json();
        })
        .then(data => {
            setButtonStatus('#subjx', false, '<i class="bi bi-scissors me-1"></i> 开始去水印');
            if (data.code === 200) {
                const result = data.data;
                const share_url = url;

                // 渲染作者信息
                document.getElementById('authorAvatar').src = result.author?.avatar || 'https://via.placeholder.com/40';
                document.getElementById('authorName').textContent = result.author?.name || '未知作者';
                document.getElementById('authorInfo').classList.remove('d-none');
                document.getElementById('authorInfo').classList.add('d-flex');

                // 渲染标题
                document.getElementById('titleText').textContent = result.title || '无标题内容';
                document.getElementById('contentTitle').classList.remove('d-none');

                // 渲染封面链接
                document.getElementById('coverUrl').textContent = result.cover_url || '';
                if(result.cover_url){
                    const coverImg = document.getElementById('coverImage');
                    coverImg.src = result.cover_url;
                    document.getElementById('coverPreview').classList.remove('d-none');
                }

                document.getElementById('resourceUrls').style.display = 'block';


                document.getElementById('resourceUrls').classList.remove('d-none');

                // 处理视频类型
                if (result.video_url) {
                    const videoUrl = result.video_url.trim();
                    const media = document.getElementById('media');
                    const videoLoading = document.getElementById('videoLoading');
                    const videoError = document.getElementById('videoError');
                    const manualGuide = document.getElementById('manualGuide');
                    const videoPlayer = document.getElementById('videoPlayer');
                    const videoWrap = document.getElementById('videoWrap');

                    // 填充视频源
                    document.getElementById('videoSourceMain').src = videoUrl;
                    document.getElementById('videoSourceBackup').src = videoUrl;

                    // 填充视频链接和下载地址
                    document.getElementById('videoUrl').textContent = videoUrl;
                    const downloadUrl = `/video/download?url=${encodeURIComponent(videoUrl)}&referer=${encodeURIComponent(share_url)}`;
                    document.getElementById('videoDownload').href = downloadUrl;
                    document.getElementById('videoDownloadPlayer').href = downloadUrl;

                    // 显示视频区和链接卡
                    videoPlayer.classList.remove('d-none');
                    document.getElementById('videoUrlCard').classList.remove('d-none');

                    // 视频加载状态监听
                    videoLoading.classList.remove('d-none');

                    // 加载成功：隐藏加载提示
                    media.addEventListener('loadeddata', () => {
                        videoLoading.classList.add('d-none');
                    }, { once: true });

                    // 核心修改：解码失败时隐藏视频区块
                    media.addEventListener('error', () => {
                        videoWrap.classList.add('d-none');

                        // 判断是否为解码失败（错误码4）
                        if (media.error.code === 4) {
                            // 隐藏整个视频播放区
                            videoLoading.classList.add('d-none');

                        } else {
                            // 其他错误类型处理
                            videoError.classList.remove('d-none');
                            manualGuide.classList.remove('d-none');

                            switch (media.error.code) {
                                case 1:
                                    videoError.textContent = '❌ 视频格式不支持（建议使用Chrome浏览器）';
                                    break;
                                case 2:
                                    videoError.textContent = '❌ 视频资源被拦截';
                                    break;
                                case 3:
                                    videoError.textContent = '❌ 视频加载中断（请检查网络后重试）';
                                    break;
                                default:
                                    videoError.textContent = `❌ 视频播放失败（错误码：${media.error.code}）`;
                            }
                        }
                    }, { once: true });

                    // 触发视频加载
                    media.load();

                // 处理图集类型
                } else if (result.images?.length > 0) {
                    const container = document.getElementById('imageContainer');
                    const imageCount = document.getElementById('imageCount');
                    imageCount.textContent = result.images.length;

                    result.images.forEach((img, i) => {
                        const imgUrl = img.url || '';
                        if (!imgUrl) return;

                        let ext = imgUrl.split('.').pop().split('?')[0];
                        if (!ext) ext = 'jpg';
                        const filename = `图集_${i + 1}.${ext}`;
                        const downloadUrl = `/video/download?url=${encodeURIComponent(imgUrl)}&referer=${encodeURIComponent(share_url)}`;
                        const imgCard = document.createElement('div');
                        imgCard.className = 'card shadow-sm';
                        imgCard.style.width = '180px';
                        imgCard.innerHTML = `
                            <div class="ratio ratio-4x3 overflow-hidden border-bottom">
                                <img src="${imgUrl}"
                                     class="card-img-top object-cover"
                                     loading="lazy"
                                     alt="图集${i + 1}"
                                     style="height: 220px;">
                            </div>
                            <div class="card-body p-2">
                                <div class="d-flex gap-1">
                                    <a href="${downloadUrl}"
                                       class="btn btn-sm btn-warning text-white w-50"
                                       target="_blank"
                                       download="${filename}">
                                        <i class="bi bi-download me-1"></i> 下载
                                    </a>
                                    <button class="btn btn-sm btn-primary text-white w-50 copy-btn"
                                            data-target="imgUrl-${i}">
                                        <i class="bi bi-clipboard me-1"></i> 复制
                                    </button>
                                </div>
                                <code id="imgUrl-${i}" class="d-none">${imgUrl}</code>
                            </div>
                        `;

                        // 同时确保卡片容器有合适的样式
                        imgCard.className = 'card mb-3';
                        imgCard.style.width = '160px';
                        imgCard.style.display = 'inline-block';
                        imgCard.style.margin = '0 8px 8px 0';
                        container.appendChild(imgCard);
                    });

                    document.getElementById('imageGallery').classList.remove('d-none');
                }

                message('success', data.msg || '解析成功！');
            }
            else if (data.code === 106) {
                message('error', data.msg || '解析失败，请重试！');
                window.location.href = '/user/login';
            }
            else if (data.code === 107) {
                message('error', data.msg || '解析失败，请重试！');
                window.location.href = '/user/getapi';
            }
            else {
                message('error', data.msg || '解析失败，请重试！');
            }
        })
        .catch(error => {
            setButtonStatus('#subjx', false, '<i class="bi bi-scissors me-1"></i> 开始去水印');
            message('error', '网络异常：' + error.message + '，请检查网络后重试！');
        });
    });

    // 回车键触发解析
    document.getElementById('url').addEventListener('keydown', (e) => {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            document.getElementById('subjx').click();
        }
    });
</script>
{% endblock %}
